package io.sundial.conversion.jackson;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import io.sundial.conversion.Converter;
import io.sundial.conversion.exception.DeserializeException;
import io.sundial.conversion.exception.SerializeException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * XML转换器
 *
 * @author Payne 646742615@qq.com
 * 2018/12/25 15:40
 */
public class XmlConverter implements Converter {
    private XmlMapper xmlMapper = new XmlMapper();

    @Override
    public String getContentType() {
        return "application/xml";
    }

    @Override
    public byte[] serialize(Object obj) throws SerializeException {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ) {
            xmlMapper.writeValue(bos, obj);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new SerializeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> type) throws DeserializeException {
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(data)
        ) {
            return xmlMapper.readValue(bis, type);
        } catch (IOException e) {
            throw new DeserializeException(e);
        }
    }

    public XmlMapper getXmlMapper() {
        return xmlMapper;
    }

    public void setXmlMapper(XmlMapper xmlMapper) {
        this.xmlMapper = xmlMapper;
    }
}
